package com.bst.bsj.portal.util;

import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.ui.ModelMap;

import com.homewaimai.common.lang.FormaterParseUtil;
import com.homewaimai.common.lang.StringUtil;
import com.homewaimai.framework.web.request.session.LoginUser;

public class ControllerUtil {

	public static final Log logger = LogFactory.getLog(ControllerUtil.class);

	public static final String COOKIE_EXTRA = "extraInfo";

	public static String returnJsonResult(String code, Object data) {

		try {

			return new String((new JsonSerializable()).serialize(code, data),
					"UTF-8");

		} catch (UnsupportedEncodingException e) {

		}

		return new String((new JsonSerializable()).serialize(code, data));
	}

	/**
	 * 获取所有参数
	 * 
	 * @param request
	 * @return
	 */
	public static Map<String, Object> getAllParams(HttpServletRequest request) {

		Map<String, Object> paramMap = new HashMap<String, Object>();

		for (Object obj : request.getParameterMap().keySet()) {
			paramMap.put((String) obj, ((String[]) request.getParameterMap()
					.get(obj))[0]);
		}
		return paramMap;
	}

	/**
	 * 获取登录用户
	 * 
	 * @param request
	 * @return
	 */
	public static LoginUser getLoginUser(HttpServletRequest request) {

		String loginUserStr = (String) request.getSession().getAttribute(
				com.homewaimai.framework.web.Constants.COOKIE_LOGIN_USER);
		if (StringUtil.isBlank(loginUserStr)) {
			return null;
		}

		LoginUser loginUser =  convertLoginUserFromCookie(loginUserStr);

		if (StringUtil.isBlank(loginUser.getMemberId())) {
			return null;
		}

		return loginUser;
	}
	
	
    public static boolean isLogined(HttpServletRequest request) {
        String loginUserStr = (String) request.getSession().getAttribute(com.homewaimai.framework.web.Constants.COOKIE_LOGIN_USER);
        if (StringUtil.isBlank(loginUserStr)) {
            return false;
        }
        LoginUser loginUser = convertLoginUserFromCookie(loginUserStr);
        if (StringUtil.isBlank(loginUser.getMemberId())) {
            return false;
        }

        return true;
    }
	

	/**
	 * 获取通用工具
	 * 
	 * @return
	 */
	public static Map<String, Object> getCommonParams() {

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("formater", FormaterParseUtil.getInstatnce());
		map.put("webUtil", WebUtil.getInstatnce());

		return map;
	}
	
	/**
	 * 输出
	 * 
	 * @param response
	 * @param result
	 */
	public static void write(HttpServletResponse response, String result) {

		response.setContentType("text/html;charset=utf-8");
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		Writer wr = null;

		try {

			wr = response.getWriter();
			wr.write(result);
			wr.flush();

		} catch (Exception e) {

			logger.error("write error: ", e);

			try {
				wr.write(new String((new JsonSerializable()).serialize("500",
						"excute  error!"), "UTF-8"));
				wr.flush();
			} catch (Exception e1) {
				logger.error(e1);
			}

		} finally {
			try {

				if (wr != null) {
					wr.close();
				}

			} catch (Exception e1) {
				logger.error(e1);
			}
		}
	}

	public static void fillParams(Object obj, ModelMap modelMap)
			throws IllegalArgumentException, IllegalAccessException {

		List<Field> fields = new ArrayList<Field>();
		// 获取所有字段对象
		getObjectAllFields(obj.getClass(), fields);

		for (Field field : fields) {

			field.setAccessible(true);
			// 反射获取字段值
			Object value = field.get(obj);

			if (value != null) {
				modelMap.addAttribute(field.getName(), value);
			}
		}
	}

	/**
	 * 获取类所有字段 包括父类
	 * 
	 * @param cclz
	 * @param fields
	 */
	public static void getObjectAllFields(Class cclz, List<Field> fields) {

		Field[] fs = cclz.getDeclaredFields();

		if (fs != null && fs.length > 0) {

			for (Field f : fs) {
				fields.add(f);
			}
		}

		Class pclz = cclz.getSuperclass();

		if (pclz != null && !pclz.isInterface()) {

			getObjectAllFields(pclz, fields);
		}
	}

	

	/**
	 * 检测商品维度
	 * 
	 * @param pdims
	 * @return
	 */

	/**
	 * 是否有空串
	 * 
	 * @param strs
	 * @return
	 */
	public static boolean existEmptyString(String... strs) {

		for (String item : strs) {
			if (StringUtil.isBlank(item)) {
				return true;
			}
		}

		return false;
	}

	public static LoginUser convertLoginUserFromCookie(String loginUserStr) {

		if (StringUtil.isBlank(loginUserStr)) {
			return null;
		}

		String[] cookies = loginUserStr.split("&");
		Map<String, String> map = new HashMap<String, String>(cookies.length);
		for (String cooke : cookies) {
			String[] keyValue = cooke.split("=");
			if (keyValue.length >= 2) {
				map.put(keyValue[0], keyValue[1]);
			}
		}
		LoginUser loginUser = new LoginUser();
		loginUser.setLogined(Boolean.parseBoolean(map
				.get(LoginUser.COOKIE_LOGINED)));
		loginUser
				.setLoginId(Long.parseLong(map.get(LoginUser.COOKIE_LOGIN_ID)));
		loginUser.setMemberId(map.get(LoginUser.COOKIE_M_ID));
		loginUser.setmLevel(map.get(LoginUser.COOKIE_M_LEVEL));
		loginUser.setTs(map.get(LoginUser.COOKIE_TS));
		loginUser.setNickName(map.get(LoginUser.COOKIE_NICK_NAME));
		return loginUser;
	}

	/**
	 * 获取URL参数
	 * 
	 * @param request
	 * @return
	 */
	public static String getUrlParams(ServletRequest request) {
		Map kvs = request.getParameterMap();
		if (kvs == null || kvs.isEmpty()) {
			return "";
		}

		StringBuilder ps = new StringBuilder();
		for (Object item : kvs.entrySet()) {
			Entry kv = (Entry) item;
			String[] values = (String[]) kv.getValue();
			String value = values == null || values.length == 0 ? ""
					: values[0];

			ps.append(kv.getKey() + "=" + value).append("&");
		}

		if (ps.length() > 0) {
			ps.deleteCharAt(ps.length() - 1);
		}

		return "?" + ps.toString();
	}

	public static boolean showWeixinPay(HttpServletRequest request, String type) {

		String extraInfo = (String) request.getSession().getAttribute(
				COOKIE_EXTRA);
		if (StringUtil.isBlank(extraInfo)) {
			return true;
		}

		return !extraInfo.equals(type);

	}

}
